package com.listeningframework.boot.commons.string;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.lang3.StringUtils;

/**
 * XML工具类
 */
public class XstreamUtils {
    /**
     * 创建XStream
     */
    private static XStream createXstream() {
        XstreamXppDriver xppDriver = new XstreamXppDriver();
        xppDriver.setCheckByType();
        return new XStream(xppDriver);
    }

    /**
     * 对象转换成XML
     *
     * @param obj 对象
     * @param cls 注解类型
     * @return String
     */
    public static String toXML(Object obj, Class<?> cls) {
        if (obj == null) {
            return null;
        }
        XStream xstream = createXstream();
        xstream.processAnnotations(cls);
        return xstream.toXML(obj);
    }

    /**
     * 对象转XML
     *
     * @param obj 对象
     * @return String
     */
    public static String toXML(Object obj) {
        if (obj == null) {
            return null;
        }
        XStream xstream = createXstream();
        return xstream.toXML(obj);
    }

    /**
     * XML 转java对象
     *
     * @param xml xml内容
     * @param cls java对象类
     * @param <T> 泛型
     * @return T
     */
    @SuppressWarnings("unchecked")
    public static <T> T xml2Obj(String xml, Class<?> cls) {
        if (StringUtils.isBlank(xml)) {
            return null;
        }
        XStream xstream = new XStream();
        if (cls != null) {
            xstream.processAnnotations(cls);
        }
        return (T) xstream.fromXML(xml);
    }

    /**
     * XML转化为JAVA对象
     *
     * @param xml xml内容
     * @param <T> 泛型
     * @return T
     */
    public static <T> T xml2Obj(String xml) {
        return xml2Obj(xml, null);
    }

}
